package com.wnnight.wys.web.notice;


import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnnight.wys.entity.notice.Notice;
import com.wnnight.wys.excelHandler.NoticeHandler;
import com.wnnight.wys.groupInterface.AddGroup;
import com.wnnight.wys.groupInterface.AlterGroup;
import com.wnnight.wys.mapper.config.PropertyStaffMapper;
import com.wnnight.wys.security.JwtUtils;
import com.wnnight.wys.service.notice.NoticeService;
import com.wnnight.wys.service.notice.NoticeTypeService;
import com.wnnight.wys.vo.NoticeVo;
import com.wnnight.wys.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName: NoticeController
 * @Description: notice前端统一传来NoticeVo，
 * 里面包含notice，pageNum（默认1）和pageSize（默认5），startDate,endDate.
 * @author: xjh
 * @date: 2022/8/29-10:12
 * @version: v1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/notice/notice")
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class NoticeController {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private NoticeTypeService noticeTypeService;
    @Autowired
    private PropertyStaffMapper propertyStaffMapper;
    @Value("${wys.uploadPath}")   //application.yml文件上配置的
    private String uploadPath;   //上传的位置D:/photoNotice
    @Value("${wys.uploadPath_mapping}")
    private String uploadPath_mapping;  //

    @PreAuthorize("hasAuthority('notice:notice:add')")
    @PostMapping("/add")
    public ResultVo<?> add(@RequestBody @Validated(AddGroup.class) NoticeVo noticeVo){
        int staffId= (int)jwtUtils.getInfo(noticeVo.getJwt(),"id");
        System.out.println(staffId);
        Notice notice=new Notice();
        notice.setTitle(noticeVo.getTitle());
        notice.setType(noticeTypeService.getById(noticeVo.getTypeId()));
        notice.setUrgency(noticeVo.getUrgency());
        notice.setContentType(noticeVo.getContentType());
        notice.setCreateTime(new Date());
        notice.setReadCount(0);
        if(!noticeVo.getContent().equals("")&&noticeVo.getContent()!=null){
            notice.setContent(noticeVo.getContent());
        }
        notice.setStatus("y");
        if(!noticeVo.getImg().equals("")&&noticeVo.getImg()!=null){
            notice.setImg(noticeVo.getImg());
        }
        if(!noticeVo.getVideo().equals("")&&noticeVo.getVideo()!=null) {
            notice.setVideo(noticeVo.getVideo());
        }
        notice.setStaff(propertyStaffMapper.getById(staffId));
        noticeService.add(notice);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/down")
    public void down(HttpServletResponse response) throws IOException {
        List<Notice> list = noticeService.getAll();
        System.out.println(list);
        //返回输出流_excel格式
//        response.setContentType("application/octet-stream");
        try {
            response.setContentType("application/vnd.ms-excel");
            String fileName = URLEncoder.encode("公告信息表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Notice.class)
                    .registerWriteHandler(new NoticeHandler())
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("公告信息表")
                    .doWrite(list);
            // ExcelUtil.writerExcel(response, userList);
        }catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(response.getWriter(), ResultVo.ERROR);
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    @PostMapping("/videoupload")
    public ResultVo<?> uploadVideo(@RequestParam("files")MultipartFile file){
        //获取文件全名   file.getOriginalFilename();
        //图片上传成功后，将图片的地址写返回到前端，然后添加到数据库
        String uuidFileName="";
        if(!file.isEmpty()){
            int begin=file.getOriginalFilename().indexOf(".");
            int last=file.getOriginalFilename().length();
            String a=file.getOriginalFilename().substring(begin,last);
            uuidFileName= UUID.randomUUID().toString().replace("-","")+a;
//            log.debug("photo:{}",photoPath);
            try {
                File dest=new File(uploadPath,uuidFileName);
                String virtualUrl=uploadPath_mapping+uuidFileName;
                file.transferTo(dest);
                System.out.println(virtualUrl);
                return new ResultVo<>(virtualUrl);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultVo.FAIL;
            }
        }
        return ResultVo.FAIL;
    }

    @PostMapping("/upload")
    public ResultVo<?> uploadPhoto(@RequestParam("files")MultipartFile file){
        //获取文件全名   file.getOriginalFilename();
        //图片上传成功后，将图片的地址写返回到前端，然后添加到数据库
        String uuidFileName="";
        if(!file.isEmpty()){
            int begin=file.getOriginalFilename().indexOf(".");
            int last=file.getOriginalFilename().length();
            String a=file.getOriginalFilename().substring(begin,last);
            if(a.endsWith(".jpg")||a.endsWith(".jpeg")||a.endsWith(".png")||a.endsWith(".jpg")){
                uuidFileName= UUID.randomUUID().toString().replace("-","")+a;
                log.debug("photo:{}",uploadPath);
                try {
                    File dest=new File(uploadPath,uuidFileName);
                    file.transferTo(dest);
                    String virtualUrl=uploadPath_mapping+uuidFileName;
                    System.out.println(virtualUrl);
                    return new ResultVo<>(virtualUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultVo.FAIL;
                }
            }
        }
        return ResultVo.FAIL;
    }

    @PreAuthorize("hasAuthority('notice:notice:list')")
    @PostMapping("/getbyid")
    public ResultVo<?> getById(@RequestBody NoticeVo noticeVo){
        System.out.println(noticeVo.getId());
        return new ResultVo<>(noticeService.getById1(noticeVo.getId()));
    }

    @PreAuthorize("hasAuthority('notice:notice:update')")
    @PostMapping("/update")
    public ResultVo<?> update(@RequestBody @Validated(AlterGroup.class) NoticeVo noticeVo){
        log.debug("notice:{}",dateFormat(noticeVo));
        noticeService.update(dateFormat(noticeVo));
        return ResultVo.SUCCESS;
    }

    @PreAuthorize("hasAuthority('notice:notice:list')")
    //查询所有
    @PostMapping("/list")
    public ResultVo<?> getAll(@RequestBody NoticeVo noticeVo){
        return new ResultVo<>(noticeService.getByCondition(new Notice(),noticeVo.getPageNum(),noticeVo.getPageSize()));
    }

    @PreAuthorize("hasAuthority('notice:notice:list')")
    //条件查询
    @PostMapping("/conditionlist")
    public ResultVo<?> getByCondition(@RequestBody NoticeVo noticeVo){
        return new ResultVo<>(noticeService.getByCondition(dateFormat(noticeVo),noticeVo.getPageNum(),noticeVo.getPageSize()));
    }

    @PreAuthorize("hasAuthority('notice:notice:list')")
    @PostMapping("/conditionlist2")
    public ResultVo<?> getByCondition2(@RequestBody NoticeVo noticeVo){
        return new ResultVo<>(noticeService.getByCondition2(noticeVo,noticeVo.getPageNum(),noticeVo.getPageSize()));
    }

    @PreAuthorize("hasAuthority('notice:notice:list')")
    //时间段查询
    @PostMapping("/datelist")
    public ResultVo<?> getByDate(@RequestBody NoticeVo noticeVo){
        return new ResultVo<>(noticeService.getByStartAndEndDate
                (noticeVo.getStartDate(),noticeVo.getEndDate(),
                noticeVo.getPageNum(),noticeVo.getPageSize()));
    }

    @PreAuthorize("hasAuthority('notice:notice:list')")
    //类型id查询
    @PostMapping("/typelist")
    public ResultVo<?> getByTypeId(@RequestBody NoticeVo noticeVo){
        return new ResultVo<>(noticeService.getByTypeId
                (noticeVo.getTypeId(),
                        noticeVo.getPageNum(),noticeVo.getPageSize()));
    }

    @PreAuthorize("hasAuthority('notice:notice:delete')")
    //删除
    @PostMapping("/delete")
    public ResultVo<?> delete(@RequestBody NoticeVo noticeVo){
        noticeService.delete(noticeVo.getId());
        return ResultVo.SUCCESS;
    }


    //前端传来的noticeVo转化成Notice类
    private Notice dateFormat(NoticeVo noticeVo){
        Notice notice=new Notice();
        notice.setId(noticeVo.getId());
        notice.setTitle(noticeVo.getTitle());
        notice.setType(noticeTypeService.getById(noticeVo.getTypeId()));
        notice.setUrgency(noticeVo.getUrgency());
        notice.setContentType(noticeVo.getContentType());
        notice.setCreateTime(noticeVo.getCreateTime());
        notice.setReadCount(noticeVo.getReadCount());
        notice.setContent(noticeVo.getContent());
        notice.setStatus(noticeVo.getStatus());
        notice.setImg(noticeVo.getImg());
        notice.setVideo(noticeVo.getVideo());
        notice.setStaff(propertyStaffMapper.getById(noticeVo.getStaffId()));
        return notice;
    }
}
